package com.example.filter;

import com.example.constant.ShiroConstants;
import com.example.utils.ShiroUtils;
import com.google.code.kaptcha.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author code威
 * @version 1.0
 * @description: 登录过滤器
 * @date 2021/12/19 19:51
 */
public class VerificationCodeFilter extends AccessControlFilter {

    private boolean captchaEnabled;


    private String captchaType;


    public boolean isCaptchaEnabled() {
        return captchaEnabled;
    }

    public void setCaptchaEnabled(boolean captchaEnabled) {
        this.captchaEnabled = captchaEnabled;
    }

    public String getCaptchaType() {
        return captchaType;
    }

    public void setCaptchaType(String captchaType) {
        this.captchaType = captchaType;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        if(captchaEnabled == false || !"post".equals(httpServletRequest.getMethod().toLowerCase())){
            return true;

        }

        return verifyCode(httpServletRequest,httpServletRequest.getParameter(ShiroConstants.CURRENT_VALIDATECODE));
    }

    private boolean verifyCode(HttpServletRequest servletRequest, String verifyCode) {
        Object obj = ShiroUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        String code = obj == null ? "":String.valueOf(obj);
        // 移除验证码，不要重复使用
        servletRequest.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        //忽略大小写
        if (StringUtils.isNotBlank(verifyCode) && verifyCode.equalsIgnoreCase(code)){
            return true;
        }
        return false;
    }


    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        request.setAttribute("captchaType",captchaType);
        request.setAttribute("captchaEnabled",captchaEnabled);
        return super.onPreHandle(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        httpServletRequest.setAttribute(ShiroConstants.CURRENT_CAPTCHA,"验证码错误");
        return true;
    }
}
